package com.gress.shop.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.gress.shop.bo.*;
import com.gress.shop.bo.example.ActionExample;
import com.gress.shop.bo.example.MemberActionRelationExample;
import com.gress.shop.constants.EmailConstants;
import com.gress.shop.dao.IActionDao;
import com.gress.shop.dao.IMemberActionRelationDao;
import com.gress.shop.dao.IMemberRoleRelationDao;
import com.gress.shop.dao.IRoleActionRelationDao;
import com.gress.shop.service.inner.IMemberInternalService;
import com.gress.shop.service.IActionService;
import com.gress.shop.service.ISsoService;
import com.gress.shop.service.mail.IMailService;
import com.gress.shop.util.HappyException;
import com.gress.shop.util.ShiroUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * Created xiongwen with 2018/3/6 16:16
 * Description:
 */
@Service
public class ActionService  implements IActionService{
    @Resource
    private IMemberInternalService memberInternalService;

    @Resource
    private IActionDao actionDao;

    @Resource
    private IMemberActionRelationDao memberActionRelationDao;

    @Resource
    private IRoleActionRelationDao roleActionRelationDao;

    @Resource
    private IMemberRoleRelationDao memberRoleRelationDao;

    @Resource
    private IMailService mailService;


    @Resource
    private ISsoService ssoService;

    @Override
    public List<Action> queryAllAction() {
        ActionExample example = new ActionExample();
        example.createCriteria().andIsValidEqualTo(1);
        example.setOrderByClause("op_time desc");
        return actionDao.selectByExample(example);
    }

    @Override
    public List<Action> queryActionLikeName(String likeName) {
        ActionExample example = new ActionExample();
        example.createCriteria().andIsValidEqualTo(1).andActionNameLike(likeName);
        return actionDao.selectByExample(example);
    }

    @Override
    public Action queryActionByCode(String code) {
        ActionExample example = new ActionExample();
        example.createCriteria().andIsValidEqualTo(1).andActionCodeEqualTo(code);
        List<Action> actionList = actionDao.selectByExample(example);
        if (CollectionUtils.isEmpty(actionList)) {
            return null;
        }
        return actionList.get(0);
    }

    @Override
    public Action queryActionById(String id) {
        return actionDao.selectByPrimaryKey(id);
    }

    @Override
    public void insertAction(Action action) {
        if (null == action) {
            throw new HappyException("系统异常");
        }
        if (StringUtils.isEmpty(action.getActionCode())) {
            throw new HappyException("权限编码为空");
        }
        ActionExample example = new ActionExample();
        example.createCriteria().andActionCodeEqualTo(action.getActionCode());
        List<Action> actions = actionDao.selectByExample(example);
        if (CollectionUtils.isEmpty(actions)) {
            String email = ShiroUtil.getUser().getEmail();
            action.setCreateBy(email);
            actionDao.insertOrUpdate(action);
            mailService.sendEmailByTheal(email, EmailConstants.ActionMail.ADD_ACTION_SUBJECT, action.getActionName() + "权限已经新增成功");
        }else {
            throw new HappyException("编码已经存在库中不,不能重复使用");
        }
    }

    @Override
    @Transactional
    public void deleteByActionId(String id) {
        String email = ShiroUtil.getUser().getEmail();
        String createBy = actionDao.selectByPrimaryKey(id).getCreateBy();
        if (!org.apache.commons.lang.StringUtils.equals(email, createBy)) {
            throw new HappyException("您无权限删除");
        }
        int i = actionDao.deleteByPrimaryKey(id);
        memberActionRelationDao.deleteByActionId(id);
        if (i != 1) {
            throw new HappyException("删除失败,检查是否重复删除");
        }
    }

    @Override
    @Transactional
    public void deleteMAR(List<String> idList) {
        idList.forEach(e -> memberActionRelationDao.deleteByActionId(e));
    }

    @Override
    public void updateAction(Action action) {
        String email = ShiroUtil.getUser().getEmail();
        String createBy = actionDao.selectByPrimaryKey(action.getId()).getCreateBy();
        if (!org.apache.commons.lang.StringUtils.equals(email, createBy)) {
            throw new HappyException("您无权限修改权限,请联系：" + createBy);
        }
        if (null == actionDao.insertOrUpdate(action)) {
            throw new HappyException("系统异常");
        }
        actionDao.insertOrUpdate(action);
    }

    @Override
    public void insertMemberActionRelation(MemberActionRelation memberActionRelation) {
        memberActionRelationDao.insertOrUpdate(memberActionRelation);
    }

    @Override
    @Transactional
    public void insertMemberActionRelation(String email, String[] actionId) {
        if (actionId == null || actionId.length == 0) {
            throw new HappyException("系统异常");
        }
        Member member = memberInternalService.queryByEmail(email);
        if (member == null) {
            throw new HappyException("用户不存在");
        }
        for (int i = 0; i < actionId.length; i++) {
            if (null != memberActionRelationDao.queryMemberIdAndActionId(member.getEmail(), actionId[i])) {
                continue;
            }
            MemberActionRelation memberActionRelation = new MemberActionRelation();
            memberActionRelation.setActionId(actionId[i]);
            memberActionRelation.setMemberId(email);
            memberActionRelation.setCreateBy(ShiroUtil.getUser().getEmail());
            memberActionRelationDao.insertOrUpdate(memberActionRelation);
        }
    }

    @Override
    public List<MemberActionRelation> queryRelationByEmail(String email) {
        String memberId = memberInternalService.getMemberIdByEmail(email);
        if (StringUtils.isEmpty(memberId)) {
            return null;
        }
        return memberActionRelationDao.selectByMemberId(memberId);
    }

    @Override
    public List<MemberActionRelation> queryAllMAR() {
        MemberActionRelationExample example = new MemberActionRelationExample();
        example.createCriteria().andIsValidEqualTo(1);
        example.setOrderByClause("op_time desc");
        return memberActionRelationDao.selectByExample(example);
    }

    @Override
    public boolean checkIsExist(String actionId) {
        return actionDao.checkIsExist(actionId);
    }

    @Override
    public List<String> queryActionByEmail(String email) {
//        List<Action> backList = Lists.newArrayList();
//        String memberId = memberInternalService.getMemberIdByEmail(email);
        //set 防止重复
        Set<String> actionIdList = Sets.newHashSet();
        //1. 角色权限
        MemberRoleRelation roleRelation = memberRoleRelationDao.selectByMemberId(email);
        if (roleRelation != null) {
            String roleId = roleRelation.getRoleId();
            List<RoleActionRelation> roleActionRelations = roleActionRelationDao.selectByRoleId(roleId);
            roleActionRelations.forEach(e->actionIdList.add(e.getActionId()));
        }
        //2.额外权限表
        List<MemberActionRelation> relationList = memberActionRelationDao.selectByMemberId(email);
        relationList.forEach(e -> actionIdList.add(e.getActionId()));

        return Lists.newArrayList(actionIdList);
    }
}
